#!/usr/bin/env python
# -*- coding:utf-8 -*-

""" 
@author: zhaoqifa@baidu.com
@license: Copyright (c) 2012 Baidu.com, Inc. All Rights Reserved
"""
import sys
from threading import Thread as Thread

class KThread(Thread):
    """A subclass of Thread, with a kill() method."""
    def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None):
        Thread.__init__(self, group, target, name, args, kwargs, verbose)
        self.killed = False 

    def start(self):
        """Start the thread."""
        self.__run_backup = self.run
        self.run = self.__run # Force the Thread to install our trace.
        Thread.start(self)

    def __run(self):
        """ Hacked run function, which installs the trace."""
        sys.settrace(self.globaltrace)
        self.__run_backup()
        self.run = self.__run_backup

    def globaltrace(self, frame, why, arg):
        if why == 'call': 
            return self.localtrace
        else:   
            return None

    def localtrace(self, frame, why, arg):
        if self.killed:
            if why == 'line': 
                raise SystemExit()
        return self.localtrace

    def kill(self):
        self.killed = True
